﻿
using Geek.Server.App.Common;
using Geek.Server.App.Common.Event;
using Geek.Server.App.Common.Session;
using Geek.Server.App.Logic.Role.Base;
using Geek.Server.Core.Actors;
using Geek.Server.Core.Events;
using Geek.Server.Core.Hotfix.Agent;
using Geek.Server.Core.Net;
using Geek.Server.Core.Net.BaseHandler;
using Geek.Server.Core.Timer;
using Geek.Server.Core.Utils;
using Server.Logic.Common.Handler;
using Server.Logic.Common.Utils;
using Server.Logic.Logic.Role.Bag;
using Server.Logic.Logic.Server;

namespace Server.Logic.Logic.Role.Base
{

    public static class RoleCompAgentExt
    {
        private static readonly Logger LOGGER = LogManager.GetCurrentClassLogger();
        public static async Task NotifyClient(this ICompAgent agent, Message notify)
        {
            var roleComp = await agent.GetCompAgent<RoleCompAgent>();
            if (roleComp != null)
                roleComp.NotifyClient(notify);
            else
                LOGGER.Warn($"{agent.OwnerType}未注册RoleComp组件");
        }
    }

    public class RoleCompAgent : StateCompAgent<RoleComp, RoleState>, ICrossDay
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();


        [Event(EventID.SessionRemove)]
        private class EL : EventListener<RoleCompAgent>
        {
            protected override Task HandleEvent(RoleCompAgent agent, Event evt)
            {
                return agent.OnLogout();
            }
        }

        [Service]
        public virtual async Task<MessageErrorCode> LoginRole(NetChannel channel, long accountId = 0)
        {
            if (State.Basic == null)
            {
                if (accountId == 0)
                    return MessageErrorCode.RoleNotExists;
            
                SetAutoRecycle(false);
                
                // 创建新角色
                State.Basic = new RoleBasic
                {
                    Id = State.Id,
                    AccountId = accountId,
                    Level = 1,
                    VipLevel = 0,
                    CreateTime = DateTime.Now,
                    OfflineTime = DateTime.Now,
                };
                
                _ = new WebRoleCreateNotify
                {
                    AccountId = accountId,
                    ServerId = Settings.ServerId,
                    RoleInfo = new AccountRoleInfo
                    {
                        Id = State.Id,
                        CreateTime = DateTime.Now,
                        LastLoginTime = DateTime.Now,
                    }
                }.Execute();
            }
            else
            {
                SetAutoRecycle(false);
                
                _ = new WebRoleLoginNotify
                {
                    Id = State.Id,
                    AccountId = State.Basic.AccountId,
                    ServerId = Settings.ServerId,
                    Time = DateTime.Now
                }.Execute();
            }
            
            State.Basic.LoginTime = DateTime.Now;
            
            // 上线数据推送
            channel.Write(new RoleInfoNotify
            {
                Basic = State.Basic,
                Bag = (await GetCompAgent<BagCompAgent>()).State.Bag,
            });
                
            return 0;
        }

        public async Task OnLogout()
        {
            //移除在线玩家
            var serverComp = await ActorMgr.GetCompAgent<ServerCompAgent>();
            await serverComp.RemoveOnlineRole(ActorId);
            //下线后会被自动回收
            SetAutoRecycle(true);
            QuartzTimer.Unschedule(ScheduleIdSet);
        }

        // private ResLogin BuildLoginMsg()
        // {
        //     var res = new ResLogin()
        //     {
        //         Code = 0,
        //         UserInfo = new UserInfo()
        //         {
        //             CreateTime = State.CreateTime.Ticks,
        //             Level = State.Level,
        //             RoleId = State.RoleId,
        //             RoleName = State.RoleName,
        //             VipLevel = State.VipLevel
        //         }
        //     };
        //     return res;
        // }

        Task ICrossDay.OnCrossDay(int openServerDay)
        {
            return Task.CompletedTask;
        }

        public void NotifyClient(Message notify)
        {
            var session = SessionManager.Get(ActorId);
            session?.Channel?.Notify(notify);
        }
    }
}
